# -*-coding: utf-8 -*-
"""
    @Theme   : 分析 A 股上市公司财报近六年的数据
    @Time    : 2024/3/13 20:21
    @Author  : YamFish
    @Url     : https://www.zhihu.com/people/yamfish
"""
import os
import warnings

from analysis import ANALYSIS_CONFIGS
from analysis.analysis import FinancialAnalysis
from analysis.pre_process import init_project, output_csv_file

import click


BASE_DIR = os.path.dirname(os.path.abspath(__file__))
INPUT_DIR = os.path.join(BASE_DIR, 'input')
OUTPUT_DIR = os.path.join(BASE_DIR, 'output')

COMPANY_PATH = os.path.join(BASE_DIR, '.company')

warnings.filterwarnings('ignore')


def read_company_code():
    with open(COMPANY_PATH, 'r', encoding='utf-8') as f:
        code = f.read()
    return code


@click.group()
def cli():
    """Financial Report Analysis"""
    pass


@click.command(name='init')
@click.option('--code', required=True, help='A 股上市公司股票代码')
@click.option('--download',  is_flag=True, help='下载三大报表财务数据文件至 input 目录。')
def init(code, download):
    """在 input 目录下输出 correct.csv 以及合并后的财务数据 csv。"""
    input_dir = os.path.join(INPUT_DIR, code)
    if not os.path.exists(input_dir):
        os.makedirs(input_dir)

    output_dir = os.path.join(OUTPUT_DIR, code)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    init_project(code, download, input_dir)
    with open(COMPANY_PATH, 'w') as f:
        f.write(code)


@click.command()
@click.option('--csv',  is_flag=True, help='生成或更新 output 目录下的 CSV 数据文件。')
@click.option('--yes', is_flag=True, help='出现 Prompt 提示时，一律使用 yes 回答。')
@click.option('--output', '-o', multiple=True, help='输出指定类型的财报分析结果，默认输出全部。',
              default=('debt-lie', 'debt-quality', 'debt-effect', 'benefit', 'cash', 'all'),
              type=click.Choice(['debt-lie', 'debt-quality', 'debt-effect', 'benefit', 'cash', 'all']))
@click.option('--code', default=None, help='A 股上市公司股票代码。')
def analysis(csv, yes, output, code):
    """在 output 目录下输出 correct.csv 修正后的财务数据 csv 以及各类分析结果。"""
    if not os.path.exists(COMPANY_PATH):
        click.secho('执行财报分析前，需先完成初始化操作！', fg='red')
        return

    if code is None:
        code = read_company_code()
    output_path = os.path.join(OUTPUT_DIR, code)
    if not os.path.exists(output_path):
        os.makedirs(output_path)

    read_path = os.path.join(INPUT_DIR, code, f'{code}.csv')
    write_path = os.path.join(output_path, f'{code}.csv')

    if not os.path.exists(write_path) or csv or \
            os.path.getmtime(os.path.join(INPUT_DIR, code, 'correct.csv')) > os.path.getmtime(write_path):
        output_csv_file(code, read_path, write_path)

    for choice in output:
        if ANALYSIS_CONFIGS.get(choice):
            FinancialAnalysis(code, choice, write_path, overwrite=yes).start_analysis()


cli.add_command(init)
cli.add_command(analysis)

if __name__ == "__main__":
    cli()
